<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise 封装 AJAX</title>
</head>
<body>
    <div>
        <h2>Promise 封装 AJAX操作</h2>
        <button id="btn">点击发生 AJAX</button>
    </div>
    <script>
        // 接口地址 https://baidu.com
        const btn = document.querySelector('#btn');
        btn.addEventListener('click',function(){
            // 创建Promise
            const p = new Promise((resolve,reject) => {
            // 1. 创建对象
                const xhr =new XMLHttpRequest();
                // 2.初始化
                xhr.open('GET','https://api.github.com/users/shunwuyu');
                // 3. 发生
                xhr.send();
                // 4. 处理响应结果
                xhr.onreadystatechange = function(){  
                    if(xhr.readyState === 4){
                        // 响应码 2xx
                        if(xhr.status >= 200 && xhr.status <300){
                            // 输出响应体
                            resolve(xhr.response);
                        } else {
                            // 输出响应状态码
                            reject(xhr.status);
                        }   
                    } 
                } 
            });
            // 调用then
            p.then(value => {
                console.log(value)
            },reason => {
                console.warn(reason);
            })

    })
    </script>
</body>
</html>